package com.jeegod.ribbon.command;

import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixObservableCommand;
import org.springframework.web.client.RestTemplate;
import rx.Observable;
import rx.Subscriber;

public class HelloServiceObserveCommand extends HystrixObservableCommand {

    private RestTemplate restTemplate;

    public HelloServiceObserveCommand(String commandKey, RestTemplate restTemplate) {
        super(HystrixCommandGroupKey.Factory.asKey(commandKey));
        this.restTemplate = restTemplate;
    }

    @Override
    protected Observable construct() {

        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                try{
                    if(!subscriber.isUnsubscribed()){
                        System.out.println("方法执行...");
                        String result = restTemplate.getForEntity("http://HELLO-SERVICE1/hello", String.class).getBody();
                        //
                        subscriber.onNext(result);
                        String result1 = restTemplate.getForEntity("http://HELLO-SERVICE1/hello", String.class).getBody();
                        //
                        subscriber.onNext(result1);
                        subscriber.onCompleted();
                    }
                }catch (Exception e){
                    subscriber.onError(e);
                }
            }
        });
    }

    @Override
    protected Observable<String> resumeWithFallback(){
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                try{
                    if(!subscriber.isUnsubscribed()){
                        subscriber.onNext("error-observe");
                        subscriber.onCompleted();
                    }
                }catch (Exception e){
                    subscriber.onError(e);
                }
            }
        });
    }
}
